package com.health.ts.controller;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
 * 页面跳转
 * @author Administrator
 */
@Controller
@RequestMapping(value = "/page")
public class PageController extends BaseController {
	
	/**
	 * http 请求对象
	 */
	@Autowired
	HttpServletRequest request;
	
	/**
	 * 工程模式 dev or product
	 */
	@Value("${spring.profiles.active}")
    private String projectModel;
	
	/**
	 * 工程根路径
	 */
	@Value("${server.servlet.context-path:}")
    private String contextPath;
	
	/**
	 * 页面跳转
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/**", method = { RequestMethod.GET })
	public String toPage(Model model) {
		String url = request.getRequestURI();
		String basePath = contextPath+"/page";
		// 截取 /page后面地址，即为模板文件路径
		String path = url.substring(basePath.length() + 1, url.length());
		// 设定查询参数到模板中
		Map<String, String> parameterMap = getParameterMap(request);
		model.addAllAttributes(parameterMap);
		setProjectModel(model);
		return path;
	}
	
	 /**
     * 获取request中的参数集合转Map
     * @param request
     * @return
     */
    private Map<String, String> getParameterMap(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        Enumeration<String> paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = paramNames.nextElement();
            String[] paramValues = request.getParameterValues(paramName);
            if (paramValues.length == 1) {
                String paramValue = paramValues[0];
                if (paramValue.length() != 0) {
                    map.put(paramName, paramValue);
                }
            }
        }
        return map;
    }
	
	private void setProjectModel(Model model){
		model.addAttribute("projectModel", projectModel);
	}
}
